package com.raos.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.raos.example.listener.EmployeeListener;
import com.raos.example.model.EmployeeEntity;
import com.raos.example.service.ImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author raos
 * @email 991207823@qq.com
 * @date 2023-08-26 9:30
 */
@Service
public class ImportServiceImpl implements ImportService {
    @Autowired
    private EmployeeListener employeeListener;
    // 创建一个固定线程数的线程池进行解析excel
    private ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Override
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcelFactory.read(file.getInputStream(), EmployeeEntity.class, employeeListener).doReadAll();
    }

    // 方案3
    @Override
    public void importExcelAsync(MultipartFile file) throws IOException {
        // 开20个线程分别处理20个sheet,往list里面添加20个任务
        List<Callable<Object>> tasks = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            int num = i;
            // 添加20个线程去解析excel
            tasks.add(() -> {
                EasyExcelFactory.read(file.getInputStream(), EmployeeEntity.class, employeeListener)
                        .sheet(num).doRead();
                return null;
            });
        }

        try {
            //唤醒20个线程
            executorService.invokeAll(tasks);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    }

}
